package io.gitee.dtdage.app.boot.starter.web.common.handler;

import io.gitee.dtdage.app.boot.starter.common.context.BeanFactory;
import lombok.SneakyThrows;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * 异常处理器工厂
 *
 * @author WFT
 * @since 2024/4/15
 */
@Component
public class ExceptionHandlerFactory extends BeanFactory<Class<? extends Throwable>, ExceptionHandler<Class<? extends Throwable>>>
        implements HandlerExceptionResolver {

    @Override
    protected IllegalArgumentException illegalArgumentException() {
        return new IllegalArgumentException("未定义此异常处理器");
    }

    @Override
    public ExceptionHandler<Class<? extends Throwable>> getInstance(Class<? extends Throwable> clazz) {
        try {
            //  调用父类的方法
            return super.getInstance(clazz);
        } catch (IllegalArgumentException e) {
            //  获取父类
            Class<?> superclass = clazz.getSuperclass();
            if (superclass.equals(Object.class)) {
                throw e;
            }
            //  noinspection unchecked
            return this.getInstance((Class<? extends Throwable>) superclass);
        }
    }

    @Override
    @SneakyThrows
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object o, Exception e) {
        response.setContentType("application/json;charset=UTF-8");
        try (PrintWriter writer = response.getWriter()) {
            writer.print(this.getInstance(e.getClass()).resolve(e));
        }
        return new ModelAndView();
    }

}
